package com.git.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;
import freemarker.template.SimpleHash;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreeMarkerViewUtil extends FreeMarkerView {
	@Override
	protected void doRender(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 把model中的键值对，放到request中
		super.exposeModelAsRequestAttributes(model, request);
		// Expose all standard FreeMarker hash models.
		SimpleHash simpleHash = super.buildTemplateModel(model, request, response);

		// 从request中获得语言
		Locale locale = RequestContextUtils.getLocale(request);

		//如果model中有create_html=false，就不再生成html，而是直接返回
		if (StringUtils.equals((String)model.get("create_html"), "false")) {
			super.processTemplate(super.getTemplate(locale), simpleHash, response);
		} else {
			this.createHTML(super.getTemplate(locale), simpleHash, request, response);
		}
	}

	public void createHTML(Template template, SimpleHash simpleHash, HttpServletRequest request,
			HttpServletResponse response) throws IOException, TemplateException, ServletException {
		// 站点根目录的绝对路径
		String basePath = request.getSession().getServletContext().getRealPath("/");
		String requestHTML = this.getRequestHTML(request);
		// 静态页面绝对路径
		String htmlPath = basePath + requestHTML;
		System.out.println("静态页面绝对路径===========>>:" + htmlPath);
		File htmlFile = new File(htmlPath);
		if (!htmlFile.getParentFile().exists()) {
			htmlFile.getParentFile().mkdirs();
		}
		if (!htmlFile.exists()) {
			htmlFile.createNewFile();
		}
		Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));
		// 处理模版
		template.process(simpleHash, out);
		out.flush();
		out.close();
		/* 将请求转发到生成的htm文件 */
		request.getRequestDispatcher(requestHTML).forward(request, response);
	}

	/**
	 * 计算要生成的静态文件相对路径 因为大家在调试的时候一般在Tomcat的webapps下面新建站点目录的，
	 * 但在实际应用时直接布署到ROOT目录里面,这里要保证路径的一致性。
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return /目录/*.htm
	 */
	private String getRequestHTML(HttpServletRequest request) {
		// web应用名称,部署在ROOT目录时为空
		String contextPath = request.getContextPath();
		// web应用/目录/文件.do
		String requestURI = request.getRequestURI();
		// basePath里面已经有了web应用名称，所以直接把它replace掉，以免重复
		requestURI = requestURI.replaceFirst(contextPath, "");
		// 将.do改为.html,稍后将请求转发到此html文件
		requestURI = StringUtils.substringBeforeLast(requestURI, ".") + ".html";
		return requestURI;
	}
}